<template>
	<view class="container">
		<!-- 任务分类 -->
		<view class="categories">
			<scroll-view scroll-x="true" class="categories-scroll">
				<view 
					v-for="(category, index) in categories" 
					:key="index"
					:class="['category-item', currentCategory === category.id ? 'active' : '']"
					@tap="switchCategory(category.id)"
				>
					{{category.name}}
				</view>
			</scroll-view>
			<view class="add-category" @tap="showAddCategory">
				<text class="iconfont">+</text>
			</view>
			<view class="manage-category" @tap="showManageCategories">
				<text class="iconfont">⚙️</text>
			</view>
		</view>

		<!-- 任务列表 -->
		<view class="tasks-list">
			<!-- 添加任务按钮 -->
			<view class="add-task" @tap="showAddTask">
				<text class="add-icon">+</text>
				<text>添加新任务</text>
			</view>

			<!-- 任务列表 -->
			<view class="task-items">
				<view 
					v-for="(task, index) in filteredTasks" 
					:key="index"
					class="task-item"
				>
					<view class="task-header">
						<view class="task-checkbox" @tap="toggleTask(task)">
							<text :class="['checkbox', task.completed ? 'checked' : '']"></text>
						</view>
						<view class="task-content">
							<text :class="['task-title', task.completed ? 'completed' : '']">{{task.title}}</text>
							<text class="task-due-date" v-if="task.dueDate">截止日期：{{task.dueDate}} {{task.dueTime || '23:59'}}</text>
						</view>
						<view class="task-priority" :class="'priority-' + task.priority">
							{{getPriorityText(task.priority)}}
						</view>
					</view>
					<view class="task-footer">
						<view class="task-category" v-if="task.categoryId && currentCategory === 'all'">
							<text class="category-label">{{getCategoryName(task.categoryId)}}</text>
						</view>
						<view class="task-progress" v-if="task.subtasks && task.subtasks.length">
							<progress :percent="getTaskProgress(task)" stroke-width="3" />
							<text class="progress-text">{{getTaskProgress(task)}}%</text>
						</view>
						<view class="task-actions">
							<text @tap="editTask(task)">编辑</text>
							<text @tap="deleteTask(task)">删除</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加/编辑任务弹窗 -->
		<uni-popup ref="taskPopup" type="center">
			<view class="popup-content" @click.stop>
				<view class="popup-title">{{isEdit ? '编辑任务' : '新建任务'}}</view>
				<view class="form-group">
					<text class="form-label">任务标题</text>
					<input type="text" v-model="taskForm.title" placeholder="请输入任务标题" class="uni-input" />
				</view>
				<view class="form-group">
					<text class="form-label">所属分类</text>
					<picker :range="categoryOptions" range-key="name" :value="getCategoryIndex(taskForm.categoryId)" @change="onCategoryChange">
						<view class="picker-view">
							<text>{{getCategoryName(taskForm.categoryId) || '请选择分类'}}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
				<view class="form-group">
					<text class="form-label">截止日期</text>
					<picker mode="date" 
						:value="taskForm.dueDate" 
						:start="minDate"
						@change="onDueDateChange">
						<view class="picker-view">
							<text>{{taskForm.dueDate || '请选择日期'}}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
				<view class="form-group">
					<text class="form-label">截止时间</text>
					<picker mode="time" 
						:value="taskForm.dueTime || '23:59'" 
						@change="onDueTimeChange">
						<view class="picker-view">
							<text>{{taskForm.dueTime || '23:59'}}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
				<view class="form-group">
					<text class="form-label">优先级</text>
					<picker :range="priorityOptions" :value="taskForm.priority" @change="onPriorityChange">
						<view class="picker-view">
							<text>{{getPriorityText(taskForm.priority)}}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
				<view class="form-group">
					<text class="form-label">任务描述</text>
					<textarea v-model="taskForm.description" placeholder="请输入任务描述" class="uni-textarea"></textarea>
				</view>
				<view class="form-actions">
					<button @tap="cancelTask" class="btn-cancel">取消</button>
					<button @tap="saveTask" type="primary" class="btn-save">保存</button>
				</view>
			</view>
		</uni-popup>

		<!-- 添加分类弹窗 -->
		<uni-popup ref="categoryPopup" type="center">
			<view class="popup-content" @click.stop>
				<view class="popup-title">{{editingCategory ? '编辑分类' : '新建分类'}}</view>
				<view class="form-group">
					<text class="form-label">分类名称</text>
					<input type="text" v-model="categoryForm.name" placeholder="请输入分类名称" class="uni-input" />
				</view>
				<view class="form-actions">
					<button @tap="cancelCategory" class="btn-cancel">取消</button>
					<button @tap="saveCategory" type="primary" class="btn-save">保存</button>
				</view>
			</view>
		</uni-popup>
		
		<!-- 分类管理弹窗 -->
		<uni-popup ref="manageCategoryPopup" type="center">
			<view class="popup-content" @click.stop>
				<view class="popup-title">分类管理</view>
				<scroll-view scroll-y="true" class="categories-list">
					<view v-for="(category, index) in categoryOptions" :key="index" class="category-manage-item">
						<text class="category-name">{{category.name}}</text>
						<view class="category-actions">
							<text class="category-action" @tap="editCategory(category)">编辑</text>
							<text class="category-action delete" @tap="deleteCategory(category)">删除</text>
						</view>
					</view>
					<view v-if="categoryOptions.length === 0" class="no-categories">
						<text>暂无分类，请点击"+"添加</text>
					</view>
				</scroll-view>
				<view class="form-actions">
					<button @tap="closeManageCategories" type="primary" style="width: 100%;">关闭</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import api from '../../utils/api.js';
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
import { reminderManager } from '../../utils/reminder.js';

export default {
	components: {
		uniPopup
	},
	data() {
		return {
			minDate: this.formatDate(new Date()),
			showTaskPopup: false,
			showCategoryPopup: false,
			categories: [
				{ id: 'all', name: '全部' },
				{ id: 'work', name: '工作' },
				{ id: 'personal', name: '个人' }
			],
			currentCategory: 'all',
			editingCategory: null,
			tasks: [],
			isEdit: false,
			currentTask: null,
			taskForm: {
				title: '',
				description: '',
				dueDate: '',
				dueTime: '23:59',
				priority: 1,
				categoryId: '',
				completed: false,
				subtasks: []
			},
			categoryForm: {
				name: ''
			},
			priorityOptions: ['低', '中', '高']
		}
	},
	computed: {
		filteredTasks() {
			if (this.currentCategory === 'all') {
				return this.tasks
			}
			return this.tasks.filter(task => task.categoryId === this.currentCategory)
		},
		categoryOptions() {
			// 过滤掉"全部"分类
			return this.categories.filter(cat => cat.id !== 'all')
		}
	},
	onLoad() {
		this.loadCategories()
		this.loadTasks()
	},
	methods: {
		switchCategory(categoryId) {
			this.currentCategory = categoryId
			this.loadTasks()
		},
		showAddTask() {
			this.isEdit = false
			this.resetTaskForm()
			this.taskForm.dueDate = this.formatDate(new Date())
			this.showTaskPopup = true
			this.$refs.taskPopup.open()
			
			// 确保数据绑定正确初始化
			this.$nextTick(() => {
				this.taskForm = { ...this.taskForm }
			})
		},
		showAddCategory() {
			this.editingCategory = null;
			this.categoryForm.name = ''
			this.showCategoryPopup = true
			this.$refs.categoryPopup.open()
		},
		showManageCategories() {
			this.$refs.manageCategoryPopup.open()
		},
		closeManageCategories() {
			this.$refs.manageCategoryPopup.close()
		},
		editCategory(category) {
			this.editingCategory = category
			this.categoryForm.name = category.name
			this.$refs.manageCategoryPopup.close()
			setTimeout(() => {
				this.$refs.categoryPopup.open()
			}, 300)
		},
		deleteCategory(category) {
			uni.showModal({
				title: '确认删除',
				content: `确定要删除分类"${category.name}"吗？删除后，该分类下的任务将移至默认分类。`,
				success: (res) => {
					if (res.confirm) {
						api.deleteCategory(category.id)
							.then(response => {
								if (response.code === 200) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})
									
									// 如果删除的是当前选中的分类，切换到全部
									if (this.currentCategory === category.id) {
										this.currentCategory = 'all'
									}
									
									// 刷新分类列表和任务列表
									this.loadCategories()
									this.loadTasks()
									
									// 关闭弹窗
									this.$refs.manageCategoryPopup.close()
								}
							})
							.catch(error => {
								console.error('删除分类失败:', error)
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								})
							})
					}
				}
			})
		},
		editTask(task) {
			this.isEdit = true
			this.currentTask = task
			this.taskForm = {
				title: task.title || '',
				description: task.description || '',
				dueDate: task.dueDate || '',
				dueTime: task.dueTime || '23:59',
				priority: task.priority !== undefined ? task.priority : 1,
				categoryId: task.categoryId || this.getDefaultCategoryId(),
				completed: task.completed || false,
				subtasks: [...(task.subtasks || [])]
			}
			this.showTaskPopup = true
			this.$refs.taskPopup.open()
			
			// 确保数据绑定正确初始化
			this.$nextTick(() => {
				this.taskForm = { ...this.taskForm }
			})
		},
		deleteTask(task) {
			uni.showModal({
				title: '确认删除',
				content: '是否确认删除该任务？',
				success: (res) => {
					if (res.confirm) {
						api.deleteTask(task.id)
							.then(response => {
								if (response.code === 200) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})
									
									// 删除对应的提醒
									reminderManager.removeReminder(task.id, 'task')
									
									// 刷新数据
									this.loadTasks()
								}
							})
							.catch(error => {
								console.error('删除任务失败:', error)
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								})
							})
					}
				}
			})
		},
		toggleTask(task) {
			// 直接调用 API 切换任务状态
			api.toggleTask(task.id)
				.then(response => {
					if (response.code === 200) {
						// 更新本地任务状态
						task.completed = !task.completed
						uni.showToast({
							title: task.completed ? '已完成' : '已取消完成',
							icon: 'success'
						})
						
						// 更新提醒状态
						if (task.completed) {
							reminderManager.removeReminder(task.id, 'task')
						} else {
							reminderManager.addTaskReminder(task)
						}
					} else {
						uni.showToast({
							title: '操作失败',
							icon: 'none'
						})
					}
				})
				.catch(error => {
					console.error('切换任务状态失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				})
		},
		saveTask() {
			if (!this.taskForm.title) {
				uni.showToast({
					title: '请输入任务标题',
					icon: 'none'
				})
				return
			}

			// 确保分类 ID 是字符串类型
			let categoryId = this.currentCategory === 'all' ? 
				(this.taskForm.categoryId || this.getDefaultCategoryId()) : 
				this.taskForm.categoryId || this.currentCategory
				
			// 转换为字符串类型
			categoryId = String(categoryId)
			
			console.log('保存任务，分类ID:', categoryId, '类型:', typeof categoryId)

			const taskData = {
				...this.taskForm,
				categoryId: categoryId
			}
			
			if (this.isEdit) {
				api.updateTask(this.currentTask.id, taskData)
					.then(response => {
						if (response.code === 200) {
							this.handleSaveSuccess()
							// 更新任务提醒
							if (response.data.completed) {
								reminderManager.removeReminder(response.data.id, 'task')
							} else {
								reminderManager.updateTaskReminder(response.data)
							}
						}
					})
					.catch(error => {
						this.handleSaveError(error)
					})
			} else {
				api.createTask(taskData)
					.then(response => {
						if (response.code === 200) {
							this.handleSaveSuccess()
							// 添加任务提醒
							reminderManager.addTaskReminder(response.data)
						}
					})
					.catch(error => {
						this.handleSaveError(error)
					})
			}
		},
		handleSaveSuccess() {
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			})
			
			// 刷新数据
			this.loadTasks()
			
			// 关闭弹窗
			this.showTaskPopup = false
			this.$refs.taskPopup.close()
		},
		handleSaveError(error) {
			console.error('保存任务失败:', error)
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			})
		},
		saveCategory() {
			if (!this.categoryForm.name) {
				uni.showToast({
					title: '请输入分类名称',
					icon: 'none'
				})
				return
			}

			const categoryData = {
				name: this.categoryForm.name
			}
			
			if (this.editingCategory) {
				// 更新分类
				api.updateCategory(this.editingCategory.id, categoryData)
					.then(response => {
						if (response.code === 200) {
							this.handleCategorySaveSuccess()
						}
					})
					.catch(error => {
						this.handleCategorySaveError(error)
					})
			} else {
				// 创建新分类
				api.createCategory(categoryData)
					.then(response => {
						if (response.code === 200) {
							this.handleCategorySaveSuccess()
						}
					})
					.catch(error => {
						this.handleCategorySaveError(error)
					})
			}
		},
		handleCategorySaveSuccess() {
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			})
			
			// 刷新分类列表
			this.loadCategories()
			
			// 关闭弹窗
			this.showCategoryPopup = false
			this.$refs.categoryPopup.close()
			this.editingCategory = null
		},
		handleCategorySaveError(error) {
			console.error('保存分类失败:', error)
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			})
		},
		cancelTask() {
			this.showTaskPopup = false
			this.$refs.taskPopup.close()
		},
		cancelCategory() {
			this.showCategoryPopup = false
			this.$refs.categoryPopup.close()
		},
		resetTaskForm() {
			this.taskForm = {
				title: '',
				description: '',
				dueDate: '',
				dueTime: '23:59',
				priority: 1,
				categoryId: this.currentCategory !== 'all' ? this.currentCategory : this.getDefaultCategoryId(),
				completed: false,
				subtasks: []
			}
		},
		loadTasks() {
			// 从API获取任务
			console.log('加载任务，当前分类ID:', this.currentCategory, '类型:', typeof this.currentCategory)
			api.getTasks(
				this.currentCategory === 'all' ? '' : this.currentCategory
			)
				.then(response => {
					if (response.code === 200) {
						console.log('获取到任务数据:', response.data.length, '条')
						this.tasks = response.data
					} else {
						console.error('获取任务失败:', response.message)
					}
				})
				.catch(error => {
					console.error('加载任务失败:', error)
				})
		},
		saveTasks() {
			// 保存任务到本地存储
			uni.setStorageSync('tasks', JSON.stringify(this.tasks))
		},
		getTaskProgress(task) {
			if (!task.subtasks || task.subtasks.length === 0) return 0
			const completed = task.subtasks.filter(st => st.completed).length
			return Math.round((completed / task.subtasks.length) * 100)
		},
		getPriorityText(priority) {
			return this.priorityOptions[priority] || '中'
		},
		onDueDateChange(e) {
			const selectedDate = new Date(e.detail.value)
			const today = new Date()
			today.setHours(0, 0, 0, 0)
			
			if (selectedDate < today) {
				uni.showToast({
					title: '不能选择过去的日期',
					icon: 'none'
				})
				return
			}
			
			this.taskForm.dueDate = e.detail.value
		},
		onDueTimeChange(e) {
			this.taskForm.dueTime = e.detail.value
		},
		onPriorityChange(e) {
			this.taskForm.priority = parseInt(e.detail.value)
		},
		onCategoryChange(e) {
			const index = e.detail.value
			this.taskForm.categoryId = this.categoryOptions[index].id
		},
		getCategoryIndex(categoryId) {
			if (!categoryId) return 0
			// 确保进行字符串比较
			const index = this.categoryOptions.findIndex(cat => String(cat.id) === String(categoryId))
			return index !== -1 ? index : 0
		},
		getCategoryName(categoryId) {
			if (!categoryId) return ''
			// 确保进行字符串比较
			const category = this.categories.find(cat => String(cat.id) === String(categoryId))
			return category ? category.name : ''
		},
		getDefaultCategoryId() {
			// 返回第一个非"全部"的分类ID，如果没有则返回空字符串
			return this.categoryOptions.length > 0 ? this.categoryOptions[0].id : ''
		},
		formatDate(date) {
			const year = date.getFullYear()
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		loadCategories() {
			api.getCategories()
				.then(response => {
					if (response.code === 200) {
						console.log('获取到分类数据:', response.data)
						// 确保所有分类 ID 都是字符串类型
						const categories = response.data.map(cat => ({
							id: String(cat.id),  // 转换为字符串
							name: cat.name
						}))
						
						this.categories = [
							{ id: 'all', name: '全部' },
							...categories
						]
					}
				})
				.catch(error => {
					console.error('加载分类失败:', error)
				})
		}
	}
}
</script>

<style lang="scss">
/* 修复输入框的全局样式 */
page {
	background-color: #f5f5f5;
	height: 100%;
}

input, textarea {
	color: #333 !important;
}

/* 确保所有输入框都能正常接收输入 */
.uni-input, .uni-textarea {
	z-index: 5;
	pointer-events: auto;
}

.container {
	flex: 1;
	display: flex;
	flex-direction: column;
	padding: 20rpx;
}

.categories {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.categories-scroll {
	flex: 1;
	white-space: nowrap;
}

.category-item {
	display: inline-block;
	padding: 10rpx 30rpx;
	margin-right: 20rpx;
	border: 1px solid #ddd;
	border-radius: 30rpx;
	font-size: 28rpx;
}

.category-item.active {
	background-color: #007AFF;
	color: #fff;
	border-color: #007AFF;
}

.add-category {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f5f5f5;
	border-radius: 30rpx;
	margin-left: 20rpx;
}

.manage-category {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f5f5f5;
	border-radius: 30rpx;
	margin-left: 10rpx;
}

.tasks-list {
	flex: 1;
	background-color: #fff;
	border-radius: 20rpx;
	padding: 20rpx;
}

.add-task {
	display: flex;
	align-items: center;
	padding: 20rpx;
	border: 2px dashed #ddd;
	border-radius: 10rpx;
	margin-bottom: 20rpx;
}

.add-icon {
	font-size: 40rpx;
	margin-right: 20rpx;
	color: #999;
}

.task-item {
	padding: 20rpx;
	border-bottom: 1px solid #eee;
}

.task-header {
	display: flex;
	align-items: center;
}

.task-checkbox {
	margin-right: 20rpx;
}

.checkbox {
	display: inline-block;
	width: 40rpx;
	height: 40rpx;
	border: 2px solid #ddd;
	border-radius: 50%;
	position: relative;
}

.checkbox.checked::after {
	content: '✓';
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	color: #007AFF;
}

.task-content {
	flex: 1;
}

.task-title {
	font-size: 32rpx;
	margin-bottom: 10rpx;
}

.task-title.completed {
	text-decoration: line-through;
	color: #999;
}

.task-due-date {
	font-size: 24rpx;
	color: #666;
}

.task-priority {
	padding: 4rpx 20rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
}

.priority-0 {
	background-color: #e8f5e9;
	color: #4caf50;
}

.priority-1 {
	background-color: #fff3e0;
	color: #ff9800;
}

.priority-2 {
	background-color: #ffebee;
	color: #f44336;
}

.task-footer {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-top: 20rpx;
}

.task-category {
	margin-right: 20rpx;
}

.category-label {
	font-size: 24rpx;
	background-color: #e1f5fe;
	color: #0288d1;
	padding: 4rpx 16rpx;
	border-radius: 20rpx;
	display: inline-block;
}

.task-progress {
	flex: 1;
	margin-right: 20rpx;
}

.progress-text {
	font-size: 24rpx;
	color: #666;
	margin-left: 10rpx;
}

.task-actions {
	display: flex;
}

.task-actions text {
	margin-left: 20rpx;
	color: #007AFF;
	font-size: 28rpx;
}

.popup-content {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	width: 650rpx;
	box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
	max-height: 90vh;
	overflow-y: auto;
}

.popup-title {
	text-align: center;
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 40rpx;
	color: #333;
	position: relative;
	padding-bottom: 20rpx;
}

.popup-title::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	height: 4rpx;
	background-color: #007AFF;
}

.form-group {
	margin-bottom: 30rpx;
}

.form-label {
	display: block;
	font-size: 28rpx;
	margin-bottom: 15rpx;
	color: #333;
}

.form-picker {
	width: 100%;
}

/* uni-ui 样式类 */
.uni-input {
	height: 88rpx;
	padding: 0 30rpx;
	line-height: 88rpx;
	font-size: 28rpx;
	background-color: #f8f8f8;
	border: 1px solid #e5e5e5;
	border-radius: 8rpx;
	width: 100%;
	box-sizing: border-box;
	z-index: 1;
	overflow: hidden;
}

.uni-textarea {
	width: 100%;
	height: 200rpx;
	padding: 20rpx;
	font-size: 28rpx;
	background-color: #f8f8f8;
	border: 1px solid #e5e5e5;
	border-radius: 8rpx;
	box-sizing: border-box;
	z-index: 1;
	overflow: hidden;
}

.picker {
	display: flex;
	align-items: center;
	padding: 10rpx;
	border: 1px solid #eee;
	border-radius: 10rpx;
}

.form-actions {
	display: flex;
	justify-content: space-between;
	margin-top: 40rpx;
}

.form-actions button {
	margin: 0;
	width: 45%;
	height: 88rpx;
	line-height: 88rpx;
	font-size: 30rpx;
}

.picker-view {
	height: 88rpx;
	padding: 0 30rpx;
	border: 1px solid #e5e5e5;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 28rpx;
	background-color: #f8f8f8;
}

.picker-arrow {
	font-size: 24rpx;
	color: #666;
	margin-left: 10rpx;
}

.form-textarea {
	border: 1px solid #ddd;
	padding: 20rpx 15rpx;
	border-radius: 10rpx;
	width: 100%;
	box-sizing: border-box;
	height: 200rpx;
	font-size: 28rpx;
	background-color: #f9f9f9;
}

.btn-cancel {
	background-color: #f5f5f5;
	color: #666;
	border: 1px solid #ddd;
}

.btn-save {
	background-color: #007AFF;
	color: #fff;
}

.categories-list {
	max-height: 600rpx;
	margin-bottom: 30rpx;
}

.category-manage-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1px solid #eee;
}

.category-name {
	font-size: 30rpx;
}

.category-actions {
	display: flex;
}

.category-action {
	margin-left: 30rpx;
	color: #007AFF;
	font-size: 28rpx;
}

.category-action.delete {
	color: #ff3b30;
}

.no-categories {
	padding: 40rpx 0;
	text-align: center;
	color: #999;
}
</style> 